package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.BedDAO;
import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.dao.LeaveApplyDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.LeaveApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class LeaveApplyServiceImpl implements LeaveApplyService {
    @Autowired
    private LeaveApplyDAO leaveApplyDAO;

    @Autowired
    private ClientDAO clientDAO;

    @Autowired
    private BedDAO bedDAO;

    @Override
    public PageResponseBean<List<ClientLeaveApply>> leaveApplyPage(String name, String expectedReturnTime, String approvalStatus, String applyId, Long page, Long size) {
        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            clientQueryWrapper.like("name", name);
        } else {
            clientQueryWrapper.isNotNull("name"); // 如果没有提供名字，则查询所有客户
        }

        List<Integer> clientIds = clientDAO.selectList(clientQueryWrapper)
                .stream()
                .map(Client::getClientId)
                .toList();

        if (clientIds.isEmpty()) {
            return new PageResponseBean<>(500, "没有找到符合条件的客户");
        }
        QueryWrapper<LeaveApply> leaveApplyQueryWrapper = new QueryWrapper<>();
        leaveApplyQueryWrapper.in("client_id", clientIds).eq("is_visible", true); // 只查询可见的外出申请
        if (approvalStatus != null && !approvalStatus.isEmpty()) {
            leaveApplyQueryWrapper.eq("approval_status", approvalStatus);
        }

        // 时间处理
        if (expectedReturnTime != null && !expectedReturnTime.isEmpty()) {
            leaveApplyQueryWrapper.like("expected_return_time", expectedReturnTime);
        }

        if (applyId != null && !applyId.isEmpty()) {
            leaveApplyQueryWrapper.eq("apply_id", applyId);
        }

        leaveApplyQueryWrapper.orderBy(true,false, "leave_time"); // 按申请时间降序排列

        IPage<LeaveApply> leaveApplyIpage = new Page<>(page,size);
        IPage<LeaveApply> leaveApplies = leaveApplyDAO.selectPage(leaveApplyIpage, leaveApplyQueryWrapper);

        Set<Integer> resultsClientIds = leaveApplies.getRecords()
                .stream()
                .map(LeaveApply::getClientId)
                .collect(Collectors.toSet());
        Map<Integer, Client> clientMap = new HashMap<>();

        if (!resultsClientIds.isEmpty()) {
            QueryWrapper<Client> clientQuery = new QueryWrapper<>();
            clientQuery.in("client_id", resultsClientIds);
            List<Client> clients = clientDAO.selectList(clientQuery);
            clientMap = clients.stream()
                    .collect(Collectors.toMap(Client::getClientId, client -> client));
        }else{
            return new PageResponseBean<>(500, "没有找到符合条件的客户");
        }

        List<ClientLeaveApply> results = new ArrayList<>();
        for(LeaveApply leaveApply : leaveApplies.getRecords()) {
            ClientLeaveApply clientLeaveApply = new ClientLeaveApply();
            clientLeaveApply.setLeaveApply(leaveApply);
            clientLeaveApply.setClient(clientMap.get(leaveApply.getClientId()));
            results.add(clientLeaveApply);
        }

        PageResponseBean<List<ClientLeaveApply>> responseBean = new PageResponseBean<>();
        responseBean.setData(results);
        responseBean.setTotal(leaveApplies.getTotal());
        responseBean.setStatus(200);
        responseBean.setMsg("外出申请查询成功");
        return responseBean;
    }

    @Transactional
    @Override
    public ResponseBean<Integer> approvalLeaveApply(LeaveApply leaveApply) {
        leaveApply.setActualReturnTime(null); // 审批时不需要设置实际返回时间
        if(leaveApplyDAO.updateById(leaveApply) > 0) {
            if ("通过".equals(leaveApply.getApprovalStatus())) {
                // 如果审批通过，更新客户的外出状态
                Client client = clientDAO.selectById(leaveApply.getClientId());
                if (client != null) {
                    client.setStatus("outward");
                    if(clientDAO.updateById(client) > 0){
                        Bed bed = bedDAO.selectById(client.getBedId());
                        if (bed != null) {
                            bed.setStatus("outward");
                            if(bedDAO.updateById(bed) > 0){
                                ResponseBean<Integer> response = new ResponseBean<>();
                                response.setStatus(200);
                                response.setMsg("外出申请审批通过，客户状态已更新");
                                response.setData(1);
                                return response;
                            }else {
                                ResponseBean<Integer> response = new ResponseBean<>();
                                response.setStatus(500);
                                response.setMsg("外出申请审批通过，但更新床位状态失败");
                                return response;
                            }
                        } else {
                            ResponseBean<Integer> response = new ResponseBean<>();
                            response.setStatus(500);
                            response.setMsg("床位不存在，无法更新外出状态");
                            return response;
                        }
                    }else {
                        ResponseBean<Integer> response = new ResponseBean<>();
                        response.setStatus(500);
                        response.setMsg("外出申请错误，更新客户状态失败");
                        return response;
                    }
                }else {
                    ResponseBean<Integer> response = new ResponseBean<>();
                    response.setStatus(500);
                    response.setMsg("客户不存在，无法更新外出状态");
                    return response;
                }
            }else {
                return new ResponseBean<>(200, "外出申请审批已更新", 1);
            }
        }else {
            ResponseBean<Integer> response = new ResponseBean<>();
            response.setStatus(500);
            response.setMsg("外出申请审批失败");
            return response;
        }
    }

    @Override
    public ResponseBean<Integer> deleteLogic(Integer applyId) {
        ResponseBean<Integer> response = new ResponseBean<>();
        LeaveApply leaveApply = leaveApplyDAO.selectById(applyId);
        if (leaveApply == null) {
            response.setStatus(404);
            response.setMsg("外出申请不存在");
        }else{
            leaveApply.setVisible(false);
            int result = leaveApplyDAO.updateById(leaveApply);
            if (result > 0) {
                response.setStatus(200);
                response.setMsg("外出申请删除成功");
                response.setData(result);
            } else {
                response.setStatus(500);
                response.setMsg("外出申请删除失败");
            }
        }
        return response;
    }

    @Transactional
    @Override
    public ResponseBean<Integer> registerReturn(LeaveApply leaveApply) {
        ResponseBean<Integer> res = new ResponseBean<>();
        LeaveApply la = leaveApplyDAO.selectById(leaveApply.getLeaveId());
        la.setActualReturnTime(leaveApply.getActualReturnTime());
        Client client = clientDAO.selectById(la.getClientId());
        Bed bed = bedDAO.selectById(client.getBedId());
        bed.setStatus("occupied");
        if (bedDAO.updateById(bed) > 0) {
            if (leaveApplyDAO.updateById(la) > 0) {
                client.setStatus("active");
                if (clientDAO.updateById(client) > 0) {
                    res.setStatus(200);
                    res.setMsg("归队申请注册成功");
                    res.setData(1);
                } else {
                    res.setStatus(500);
                    res.setMsg("归队申请注册失败，更新客户状态失败");
                }
            } else {
                res.setStatus(500);
                res.setMsg("归队申请注册失败，更新外出申请状态失败");
            }
        } else {
            res.setStatus(500);
            res.setMsg("归队申请注册失败，更新床位状态失败");
        }
        return res;
    }
}
